package com.zcx.redis.controller.common;

import com.zcx.redis.bean.common.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionController extends BaseController{

    /**
     * 捕获参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
      log.error(e.toString());
      BindingResult result=e.getBindingResult();
        Map map=new HashMap();
      //获取出错的字段 参数名
       List<FieldError> list= result.getFieldErrors();
        Iterator<FieldError> it=list.iterator();
        while(it.hasNext()){
            FieldError error=it.next();
            map.put(error.getField(),error.getDefaultMessage());
        }
        return fail("验证失败",map);
    }


    @ExceptionHandler(SQLException.class)
    public ResultBean handlerSqlException(SQLException e){
        log.error("sql异常>>"+e.getMessage());
        return fail("服务器异常！");
    }

}
